package com.yzt.plugin_network;

import java.net.Proxy;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * 功能：Retrofit+OkHttp初始化类
 */
public class BaseNetLayer {

    protected OkHttpClient.Builder mOKBuilder;
    protected Retrofit.Builder mRbuilder;
    private OkHttpClient mHttpClient;
    private Retrofit mRetrofit;

    protected BaseNetLayer() {
        initOKBuilder();
        mRbuilder = new Retrofit.Builder();
    }

    protected void reset() {
        initOKBuilder();
        mRbuilder = new Retrofit.Builder();
        mHttpClient = null;
        mRetrofit = null;
    }

    void initOKBuilder() {
        if (BuildConfig.DEBUG) {
            mOKBuilder = new OkHttpClient.Builder();
        } else {
            mOKBuilder = new OkHttpClient.Builder().proxy(Proxy.NO_PROXY);
        }
    }

    public <T> T build(Class<T> service) {
        OkHttpClient mHttpClient = generateHttpClient();
        if (mRetrofit == null) {
            mRetrofit = mRbuilder
                    //设置返回类型为RXJava，或者回调`
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    //设置返回数据类型
                    .addConverterFactory(FastJsonConverterFactory.create())
                    .client(mHttpClient)
                    //设置网络请求，默认httpclient
                    .build();
        }
        return mRetrofit.create(service);
    }

    private synchronized OkHttpClient generateHttpClient() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        if (mHttpClient == null) {

            mHttpClient = mOKBuilder
                    .retryOnConnectionFailure(true)
                    .addInterceptor(loggingInterceptor)
                    .connectTimeout(TimeOutHelper.getInstance().getConnTimeOut(), TimeUnit.MILLISECONDS)
                    .readTimeout(TimeOutHelper.getInstance().getReadTimeOut(), TimeUnit.MILLISECONDS)
                    .writeTimeout(TimeOutHelper.getInstance().getWriteTimeOut(), TimeUnit.MILLISECONDS)
                    .build();
        }
        return mHttpClient;
    }
}
